<template>
    <a-modal
        :keyboard="false"
        :maskClosable="false"
        :title="modelRef.orderState == 1 ? '接单' : '工单转单'"
        :open="visible"
        :width="550"
        :confirmLoading="loading"
        centered
        @ok="handleSubmit"
        @cancel="handleCancel"
    >
        <a-form layout="vertical">
            <a-row :gutter="16" type="flex" justify="start">
                <!-- <a-col :xs="24" :sm="24" :md="24">
                    <a-form-item label="工单分类" v-bind="validateInfos.orderClassifyNameOld">
                        <a-input v-model:value="modelRef.orderClassifyNameOld" disabled></a-input>
                    </a-form-item>
                </a-col> -->
                <a-col :xs="24" :sm="24" :md="24">
                    <a-form-item label="工单分类" v-bind="validateInfos.orderClassifyId">
                        <a-select v-model:value="modelRef.orderClassifyId" @change="handleClassifyIdChange" style="width: 100%">
                            <a-select-option v-for="(item, index) in cateData" :key="index" :value="item.id">{{ item.classifyName }}</a-select-option>
                        </a-select>
                    </a-form-item>
                </a-col>
                <a-col :xs="24" :sm="24" :md="24">
                    <a-form-item label="是否转负责人接单" v-bind="validateInfos.upgradeHandler">
                        <a-radio-group v-model:value="modelRef.upgradeHandler" @change="handleChange">
                            <a-radio :value="1">是</a-radio>
                            <a-radio :value="0">否</a-radio>
                        </a-radio-group>
                    </a-form-item>
                </a-col>
                <a-col :xs="24" :sm="24" :md="24">
                    <a-form-item label="接单人" v-bind="validateInfos.orderChargePersonId">
                        <a-select v-model:value="modelRef.orderChargePersonId" @change="handlePersonChange">
                            <a-select-option v-for="(item, index) in sourceData" :key="index" :value="item.id">{{ item.name }}</a-select-option>
                        </a-select>
                    </a-form-item>
                </a-col>
            </a-row>
        </a-form>
    </a-modal>
</template>

<script lang="ts">
    import type { PropType } from 'vue';
    import { defineComponent, reactive, ref, watchEffect, watch, nextTick } from 'vue';
    import { Form, message } from 'ant-design-vue';
    import { cloneDeep, isEmpty } from 'lodash-es';
    import { getTakingPersonUpgrade, transferOrderDJD, transferOrderCLZ, getTakingPerson } from '@/api/order/mine-list';
    import { getListToConvert } from '@/api/order/cate';
    import { useUserStore } from '@/store/user';
    const userStore = useUserStore();

    export default defineComponent({
        props: {
            visible: {
                type: Boolean,
                required: true,
            },
            model: {
                type: Object as PropType<any>,
                default: () => null,
            },
        },
        emits: ['cancel', 'success'],
        setup(props, { emit }) {
            const loading = ref(false);

            const sourceData = ref<any[]>([]);
            const cateData = ref<any[]>([]);
            const defaultForm = {
                orderClassifyId: '',
                upgradeHandler: '',
                orderChargePersonId: '',
            };
            const modelRef = reactive<any>(cloneDeep(defaultForm));
            const rulesRef = reactive({
                orderClassifyId: [{ required: true, message: '请选择' }],
                upgradeHandler: [{ required: true, message: '请选择' }],
                orderChargePersonId: [{ required: true, message: '请选择' }],
            });
            const { validateInfos, resetFields, validate } = Form.useForm(modelRef, rulesRef);

            // 记录初始值
            const initValues = reactive({});
            watch(
                () => props.visible,
                () => {
                    Object.assign(initValues, cloneDeep(props.model));
                    console.log('props.model', props.model);

                    const { orderClassifyName, orderState, orderChargePersonId, orderChargePerson, orderClassifyId } = props.model;
                    Object.assign(modelRef, props.model, {
                        orderClassifyId,
                        upgradeHandler: 0,
                        orderClassifyNameOld: orderClassifyName,
                        orderChargePersonIdOld: orderChargePersonId,
                        orderChargePersonOld: orderChargePerson,
                        orderChargePersonId: null,
                        orderChargePerson: null,
                    });
                    console.log(modelRef);
                    // orderState 工单状态，1待接单、2处理中、3待审核、4已审核、5待评价、6已完成
                    // if (orderState === 1) {
                    //     handleChange(0);
                    // } else {
                    //     handleChange(0);
                    // }
                    handleChange(0);

                    getListToConvert(modelRef.id).then(res => {
                        cateData.value = res.data;
                    });
                },
            );
            watchEffect(() => {
                if (props.visible) {
                    if (props.model) {
                    }
                }
            });

            const handleClassifyIdChange = (val, options) => {
                // nextTick(() => {
                const cate = cateData.value.find(item => item.id === val);
                modelRef.orderProfessionalLine = cate.orderProfessionalLine;
                modelRef.orderClassifyName = cate.classifyName;
                modelRef.orderClassifyId = val;
                modelRef.orderChargePersonId = '';
                modelRef.orderChargePerson = '';
                getUserList();
                // });
            };
            const handlePersonChange = val => {
                const person = sourceData.value.find(item => item.id === val);
                modelRef.orderChargePerson = person.name;
            };

            const handleChange = val => {
                modelRef.orderChargePersonId = '';
                modelRef.orderChargePerson = '';
                getUserList();
            };
            const getUserList = () => {
                if (modelRef.upgradeHandler === 1) {
                    getTakingPersonUpgrade({
                        orderId: modelRef.id,
                        orderProfessionalLine: modelRef.orderProfessionalLine,
                    }).then(res => {
                        sourceData.value = res.data;
                        const find = res.data.find(item => userStore.info.user.id == item.id);
                        if (find) {
                            modelRef.orderChargePersonId = userStore.info.user.id;
                            modelRef.orderChargePerson = userStore.info.user.nickname;
                        }
                    });
                } else {
                    getTakingPerson({
                        orderId: modelRef.id,
                        orderProfessionalLine: modelRef.orderProfessionalLine,
                    }).then(res => {
                        sourceData.value = res.data;
                        const find = res.data.find(item => userStore.info.user.id == item.id);
                        if (find) {
                            modelRef.orderChargePersonId = userStore.info.user.id;
                            modelRef.orderChargePerson = userStore.info.user.nickname;
                        }
                    });
                }
            };

            const handleCancel = () => {
                resetFields();
                Object.keys(modelRef).forEach(key => {
                    delete modelRef[key];
                });
                Object.assign(modelRef, cloneDeep(defaultForm));

                modelRef.status = 1;
                emit('cancel');
            };

            const handleSubmit = async () => {
                validate().then(() => {
                    loading.value = true;
                    const {
                        id: orderId,
                        orderState,
                        orderChargePersonId,
                        orderChargePerson,
                        orderClassifyNameOld,
                        orderClassifyId,
                        orderClassifyName,
                        orderProfessionalLine,
                        upgradeHandler,
                        orderChargePersonIdOld,
                        orderChargePersonOld,
                    } = modelRef;
                    const params: any = {
                        orderId,
                        orderChargePersonId,
                        orderChargePerson,
                        orderProfessionalLine,
                        orderClassifyId,
                    };
                    Object.assign(params, {
                        orderClassifyNameOld,
                        orderClassifyName,
                        upgradeHandler,
                        orderChargePersonIdOld,
                        orderChargePersonOld,
                    });
                    (orderState === 1 ? transferOrderDJD : transferOrderCLZ)(params)
                        .then(() => {
                            message.success('操作成功');
                            emit('success');
                            handleCancel();
                        })
                        .finally(() => {
                            loading.value = false;
                        });
                });
            };
            return {
                userStore,
                loading,

                modelRef,
                validateInfos,
                resetFields,

                handleSubmit,
                handleCancel,

                initValues,
                sourceData,
                cateData,
                isEmpty,
                handleChange,
                handleClassifyIdChange,
                handlePersonChange,
            };
        },
        components: {},
    });
</script>
